package com.baizhi.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baizhi.entity.User;
import com.baizhi.service.UserService;
import com.baizhi.utils.JWTUtils;
import com.baizhi.utils.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: dlh
 * @Date: 2020/11/12
 * @Descible:
 * @ClassName: UserController
 * @Version:1.0
 */
@RestController
@RequestMapping("user")
@CrossOrigin
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("login")
    public Map<String, Object> login(@RequestBody User user) {
        log.info("用户信息:[{}]", user.toString());
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            User userDB = userService.login(user);
            Map<String, String> payload = new HashMap<>();
            payload.put("id", userDB.getId());
            payload.put("username", userDB.getUsername());
            //生成token
            String token = JWTUtils.getToken(payload);
            log.info("当前token:[{}]", token);
            map.put("state", true);
            map.put("msg", "提示:登录成功");
            map.put("user", userDB);
            map.put("token", token);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", false);
            map.put("msg", "提示:登录失败" + e.getMessage());
        }
        return map;
    }

    /**
     * 用户注册
     */
    @PostMapping("register")
    public Map<String, Object> Register(@RequestBody User user, String code, HttpServletRequest request) {
        log.info("用户信息：[{}]", user.toString());
        log.info("用户输入的验证码信息:[{}]", code);
        Map<String, Object> map = new HashMap<String, Object>();
        //调用业务方法
        try {
            String key = (String) request.getServletContext().getAttribute("code");
            if (key.equalsIgnoreCase(code)) {
                userService.save(user);
                map.put("state", true);
                map.put("msg", "提示:注册成功！！！");
            } else {
                throw new RuntimeException("验证码出现错误！！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", false);
            map.put("msg", "提示:注册失败" + e.getMessage());
        }
        return map;
    }

    @PostMapping("test")
    public Map<String, Object> test(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        String token = request.getHeader("token");
        DecodedJWT verifyToken = JWTUtils.verifyToken(token);
        log.info("用户id:[{}]",verifyToken.getClaim("id").asString());
        log.info("用户name:[{}]",verifyToken.getClaim("username").asString());
        map.put("state", true);
        map.put("msg", "请求成功！！");
        return map;
    }

    /**
     * 生成验证码图片
     */
    @GetMapping("getImage")
    public String getImageCode(HttpServletRequest request) throws IOException {
        //1.使用工具类生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //2.将验证码放入servletContext作用域
        request.getServletContext().setAttribute("code", code);
        //3.将图片转为base64
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(120, 30, byteArrayOutputStream, code);
        return "data:image/png;base64," + Base64Utils.encodeToString(byteArrayOutputStream.toByteArray());
    }

}
